#include "Vector2D.h"
#include <math.h>

const float RAD_TO_DEG = 57.29578;

Vector2D Vector2D::Add(const Vector2D& left, const Vector2D& right)
{
	Vector2D add;
	add.x = left.x + right.x;
	add.y = left.y + right.y;
	return add;
}

Vector2D Vector2D::Substract(const Vector2D& left, const Vector2D& right)
{
	Vector2D substract;
	substract.x = left.x - right.x;
	substract.y = left.y - right.y;
	return substract;
}

Vector2D Vector2D::Scale(const Vector2D& vect, float scale)
{
	Vector2D grandeur;
	grandeur.x = vect.x * scale;
	grandeur.y = vect.y * scale;
	return grandeur;
}

void Vector2D::MoveBy(const Vector2D& by, /*ES*/ Vector2D& toMove)
{
	toMove.x = toMove.x + by.x;
	toMove.y = toMove.y + by.y;
}

float Vector2D::GetPolarAngleDeg(const Vector2D& vect)
{
	if (vect.x >= 0)
	{
		if (vect.y >= 0)
			return RAD_TO_DEG * atan (abs(vect.y) / abs(vect.x));
		else
			return 360 - RAD_TO_DEG * atan (abs(vect.y) / abs(vect.x));
	}
	else
	{
		if (vect.y >= 0)
			return 180 - RAD_TO_DEG * atan (abs(vect.y) / abs(vect.x));
		else
			return 180 - RAD_TO_DEG * atan (abs(vect.y) / abs(vect.x));
	}
}

float Vector2D::AngleBetweenDeg(const Vector2D& left, const Vector2D& right)
{
	float leftAngDeg, rightAngDeg;

	leftAngDeg = GetPolarAngleDeg(left);
	rightAngDeg = GetPolarAngleDeg(right);

	if (leftAngDeg > rightAngDeg)
		return leftAngDeg - rightAngDeg;
	else
		return rightAngDeg - leftAngDeg;
}

float Vector2D::Length(const Vector2D& vect)
{
	return sqrt(vect.x * vect.x + vect.y * vect.y);	
}

float Vector2D::LengthSq(const Vector2D& vect)
{
	return vect.x * vect.x + vect.y * vect.y;
}

bool Vector2D::Normalize(/*ES*/ Vector2D& vect)
{
	float Longueur = Length(vect);

	if (Longueur == 0)
		return false;
	vect.x = vect.x/Longueur;
	vect.y = vect.y/Longueur;
	return true;
}

void Vector2D::ScaleBy(Vector2D& vect, float scale)
{
	vect.x *= scale;
	vect.y *= scale;
}

Vector2D Vector2D::GetVectorByAngleDeg(float angle)
{
	angle = fmod(angle, 360);
	if (angle == 0)
	{
		Vector2D vect = {1, 0};
		return vect;
	}

	if (angle == 90)
	{
		Vector2D vect = {0, 1};
		return vect;
	}

	if (angle == 180)
	{
		Vector2D vect = {-1, 0};
		return vect;
	}

	if (angle == 270)
	{
		Vector2D vect = {0, -1};
		return vect;
	}

	Vector2D vect = {cos(angle / RAD_TO_DEG), sin(angle / RAD_TO_DEG)};
	return vect;
}

bool Vector2D::Equals(const Vector2D& left, const Vector2D& right)
{
	if (abs(left.x - right.x) < EPSILON && abs(left.y - right.y) < EPSILON)
		return true;
	return false;
}
